import time
import json
from django.utils.deprecation import MiddlewareMixin
from backend.models import BackendLog
from django.conf import settings


# 解决跨域
class CorsMiddleWare(MiddlewareMixin):
    def process_response(self, request, response):
        if request.method == "OPTIONS":
            # 可以加*
            response["Access-Control-Allow-Headers"] = "*"
            response['Access-Control-Allow-Methods'] = '*'
        response["Access-Control-Allow-Origin"] = "*"
        return response


class BackendLogMiddleWare(MiddlewareMixin):
    # 不进行记录的ip
    # exclude_ip = []

    def __init__(self, *args):
        super().__init__(*args)
        # 进入时间
        self.start_time = None
        # 离开时间
        self.end_time = None
        # 携带数据
        self.data = {}

    def process_request(self, request):
        self.start_time = time.time()
        # print(request.build_absolute_uri())
        # 请求路径
        path = request.path
        # 请求方法
        method = request.method
        # 请求参数  # django将参数放在get或post中
        parameter = request.GET if method == 'GET' else request.POST
        # 请求ip
        addr = request.META.get('REMOTE_ADDR')
        # ua
        user_agent = request.META.get('HTTP_USER_AGENT')
        self.data.update({
            'path': path,
            'method': method,
            'parameter': parameter,
            'addr': addr,
            'user_agent': user_agent,
        })

    def process_view(self, request, view_func, view_args, view_kwargs):
        # 获取视图的信息
        view_name = view_func.__name__
        self.data['view'] = view_name
        self.data['view_args'] = view_args
        self.data['view_kwargs'] = view_kwargs

    def process_response(self, request, response):
        if request.method == 'OPTIONS' or request.path.startswith(settings.MEDIA_URL):
            # 如果是预检请求或者媒体文件请求，直接跳过
            return response
        try:
            status = json.loads(response.content).get('code')
        except:
            status = 1099
        self.data['status'] = status
        user = request.user.id if request.user else 'AnonymousUser'
        self.data['user'] = user
        self.end_time = time.time()
        # 花费时间
        expend_time = self.end_time - self.start_time
        self.data['expend_time'] = round(expend_time, 3)
        BackendLog.objects.create(**self.data)
        return response
